package com.gome.security.util.cert;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Encoder;

public class Demo {
	
	public static void main(String[] args) throws Exception {
		
		
		// 读取keystore文件到KeyStore对象
	    FileInputStream in = new FileInputStream("d:/keydsa/demo.keystore");
	    KeyStore ks = KeyStore.getInstance("JKS");// JKS: Java Key StoreJKS，可以有多种类型
	    ks.load(in, "123456".toCharArray());
	    in.close();        
	 
	    // 从keystore中读取证书和私钥
	    String alias = "rb";  // 记录的别名
	    String pswd = "123456";    // 记录的访问密码        
	    java.security.cert.Certificate cert = ks.getCertificate(alias);
	    PublicKey publicKey = cert.getPublicKey();
	    BASE64Encoder bse = new BASE64Encoder();
		String pk = Base64.encodeBase64String(publicKey.getEncoded());//bse.encode(publicKey.getEncoded());
	    PrivateKey privateKey = (PrivateKey) ks.getKey(alias, pswd.toCharArray());  
	    BASE64Encoder bsei = new BASE64Encoder();
	    String pik = Base64.encodeBase64String(privateKey.getEncoded());//bsei.encode(privateKey.getEncoded());
	    System.out.println(pk);
	    System.out.println(pik);
	    
	    
	    
	    
		CertificateFactory of;
		String bv = null;
		PublicKey puk = null;
		try {
			of = CertificateFactory.getInstance("x.509");
			FileInputStream ins = new FileInputStream("D:/keydsa/gomerb.csr");
			X509Certificate Cert = (X509Certificate) of.generateCertificate(ins);
			puk = Cert.getPublicKey();
			BASE64Encoder bs = new BASE64Encoder();
			bv = Base64.encodeBase64String(puk.getEncoded());//bs.encode(puk.getEncoded());
		} catch (Exception e) {
			e.printStackTrace();
		}
	    
		 System.out.println(bv);
	    
	    
	    
	    
	    
	}
	

}
